<?php
    /**
    * Change logs
    * Oct 7, 2011 - trungdt - Add support Flag Ajax for manual breaking normal loading
    * Apr 6, 2012 - trungdt - Add client browser detect - mobile support
    * Apr 18, 2012 - trungdt - Add Subsystem Log
    */
    header('X-UA-Compatible: IE=EmulateIE8');
    define('SCRIPT_EXP_RELATIVE','');
    define('SCRIPT_FILENAME','index.php');
    //Jan 13, sonhb - force https
    


    /**
    * Real system path cache
    * 
    * @var $path
    * @var $force_ask bool ; Force __realpath to process for the path
    */
    $__SYS_realpath="";
    function __realpath($path, $force_ask = false) {
        // Aug 8, 2012 - Add cache for system path
        if (!$force_ask)
        {
            global $__SYS_realpath;
            if ($__SYS_realpath != "")
                return $__SYS_realpath;
        }

        $path = str_replace('\\','/',realpath($path));
        if ($path{1} == ':') {
            // We can't just check for C:/, because windows users may have the IIS webroot on X: or F:, etc.
            $path = substr($path,2);
        }
        if (!$force_ask)
        {
            $__SYS_realpath = $path;

            return $__SYS_realpath;
        }
        else
            return $path;
    }
    include_once(dirname(__realpath(__FILE__)).'/exponent_bootstrap.php');

    // Initialize the language subsystem
    require_once(BASE.'subsystems/lang.php');
    // Initialize the Core Subsystem
    require_once(BASE.'subsystems/core.php');
    require_once(BASE.'subsystems/database.php');

    $db = exponent_database_connect(DB_USER,DB_PASS,DB_HOST.':'.DB_PORT,DB_NAME);

    $url=$_SERVER['REQUEST_URI'];
    if (($url == "" || $url == "/"))
    {
        // ok, to prevent cache issue, please redirect to the right URL
        // assume that mod rewrite enabled 
        $tsection=$db->selectObject("section", "id = ".SITE_DEFAULT_SECTION);
        if ($tsection)
        {
            $url = "/".$tsection->sef_name;

            // get list of all language
            $langs = exponent_lang_full();
            // determine lang_url_prefix
            if (isset($langs[$tsection->language]))
                $url="/".$langs[$tsection->language]['url_prefix'].$url;

            header("Location: {$url}");
            die();
        }
    }

    require_once(BASE.'subsystems/log.php');
    require_once(BASE.'subsystems/permissions.php');
    require_once(BASE.'subsystems/users.php');
    exponent_sessions_validate();
    // Initialize permissions variables
    exponent_permissions_initialize();

    $cache_timeout=24*60*60; // 24 hours

    /**
    * This function handle content output
    * And save page to cache file
    * 
    * @param string $content
    * @return string
    */
    function ab_gzHTML($content){
        global $canLoadCache, $cacheStillAvailable, $browser;

        if (!$browser)
            $browser = new Browser();

        // zip and minify content
        $search = array(
        '/\>[^\S ]+/s', //strip whitespaces after tags, except space
        '/[^\S ]+\</s', //strip whitespaces before tags, except space
        );
        $replace = array(
        '>',
        '<',
        );
        //$content = preg_replace($search, $replace, $content);

        // save to file if needed
        //$uri="-browser|".$browser->getBrowser()."-Version|".$browser->getVersion()."-Platform|".$browser->getPlatform();
        $uri="";
        $uri="___browser_".$browser->getBrowser()."_".$browser->getPlatform()."_".md5($_SERVER['REQUEST_URI'].$uri).".php";
        $file_path=BASE."tmp/views_c/".$uri; 
        if ($canLoadCache && (!file_exists($file_path) || 
        (filesize($file_path) != strlen($content) 
        || !$cacheStillAvailable
        ))
        && !exponent_users_isLoggedIn() && DEVELOPMENT == 0)
        {
            // write to cache file
            try{
                $file=fopen($file_path,"x");
                fwrite($file,$content);
                fclose($file);
            }
            catch (Exception $ex) {

            }

        }
        $output = ob_gzhandler($content,1);
        //$output = $content;
        header("Content-Type: text/html; charset=".LANG_CHARSET);
        header("Content-language: CONTENT='".LANG_CODE."'");
        header("Cache-Control: private, public"); 
        header("Pragma: public"); 
        header("Content-Encoding: gzip"); 

        //header("Content-Length: ".strlen($output));
        return $output;
    }


    //ob_start("ob_gzhandler");
    ob_start("ab_gzHTML");

    //$microtime_str = explode(' ',microtime());
    //$i_start = $microtime_str[0] + $microtime_str[1];
    /**
    * June 7, 2011 - trungdt - Check cache file, include it if available
    */
    //$uri="-browser|".$browser->getBrowser()."-Version|".$browser->getVersion()."-Platform|".$browser->getPlatform();
    $uri="";
    $uri="___browser_".$browser->getBrowser()."_".$browser->getPlatform()."_".md5($_SERVER['REQUEST_URI'].$uri).".php";
    $file_path=BASE."tmp/views_c/".$uri; 

    $cacheStillAvailable=true;
    if (file_exists($file_path) && (filesize($file_path) > 0)){
        $cache_lastaccess=filemtime($file_path);
        if (time()-$cache_lastaccess > $cache_timeout)
        {
            $cacheStillAvailable=false;
        }
    }
    else
    {
        $cacheStillAvailable=false;
    }

    $canLoadCache=true;
    if (($_SERVER['REQUEST_METHOD'] == "GET") || ($browser->isMobile())) // load from cache if method request is get
    {
        // this request we can load from cache?
        $cacheAvoid=include("absoft_cache_prefix.php");
        foreach ($cacheAvoid as $v)
        {
            if (strpos($_SERVER['REQUEST_URI'], $v) !== false)
            {
                $canLoadCache=false;
                break;
            }
        }
    }
    else
    {
        $canLoadCache=false;
    }

    //&& (file_exists($file_path))
    if ($canLoadCache && $cacheStillAvailable && (DEVELOPMENT == 0)  && !exponent_users_isLoggedIn() )
    {
        // before we include file, we should return page header
        exponent_lang_initialize();
        include($file_path);
    }
    /**
    * June 7, 2011 - trungdt - Check cacahe file, include it if available - END
    */
    else
    {
        // Initialize the Exponent Framework
        require_once('exponent.php');
        /**
        * June 7, 2011 - trungdt - Add html cache expires support
        */
        //header("Content-Type: text/html; charset=".LANG_CHARSET);
        //header("Content-language: CONTENT='".LANG_CODE."'");
        //header("Cache-Control: private, public"); 
        //header("Pragma: public"); 
        //header("Content-Encoding: gzip"); 
        // Apr 6, 2012 - no need to set default time zone here, just set in config
        /*if (!isset($user->time_belt)) // if this session is not logged, must set default time belt to GMT +7 Ho Chi Minh City
        date_default_timezone_set("Asia/Ho_Chi_Minh"); 
        else
        {
        //$time_belt=$user->time_belt;
        //if ($time_belt > 0)
        //	$time_belt="+".$time_belt;
        //date_default_timezone_set("Etc/GMT{$time_belt}"); 
        date_default_timezone_set("Asia/Ho_Chi_Minh"); 
        }*/

        //header("Expires: "+date("r",$theme_session_expires));
        /**
        * June 7, 2011 - trungdt - Add html cache expires support - END
        */

        /* 8/29/2009: immanuel192 add this code to support visitors count
        // clear old visitor session on visitors
        $now=time();
        $infomodule_mintimeout=15;
        $db->delete("visitors","visit < " . ($now - $infomodule_mintimeout*60));
        $infomodule_ip= $_SERVER['REMOTE_ADDR'];
        $infomodule_session=$db->selectObject("visitors", "ip = '{$infomodule_ip}' AND visit > ". ($now-$infomodule_mintimeout*60));
        if ($infomodule_session){
        // update last session only
        // save this session object inother to update it
        $infomodule_temp=null;
        $infomodule_temp->ip=$infomodule_session->ip;
        $infomodule_temp->visit=$infomodule_session->visit;
        $infomodule_session->visit=$now;
        $infomodule_session->ip=$infomodule_ip;
        $db->updateObject($infomodule_session,"visitors"," ip = '{$infomodule_temp->ip}' AND visit={$infomodule_temp->visit}"); 
        } else {
        // create new session record
        $infomodule_session->visit=$now;
        $infomodule_session->ip=$infomodule_ip;
        $db->insertObject($infomodule_session,"visitors");
        // how many time clients visited this site?
        $db->increment("visited","visited",1);
        }
        // end of 8/29/2009:
        */

        // Initialize the theme subsystem
        if (!defined('SYS_THEME')) require_once(BASE.'subsystems/theme.php');
        // Check to see if we are in maintenance mode.
        if (MAINTENANCE_MODE && !exponent_users_isAdmin() && ( !isset($_REQUEST['module']) || $_REQUEST['module'] != 'loginmodule')) {
            //only admins/acting_admins are allowed to get to the site, all others get the maintenance view
            $template = new standalonetemplate('_maintenance');
            $template->output();
        } else {
            if (MAINTENANCE_MODE > 0) flash('error', "Maintenance Mode is Enabled");
            //the default user is anonymous
            if (!exponent_sessions_loggedIn()) {
                // Initialize the users subsystem
                require_once(BASE.'subsystems/users.php');

                //TODO: Maxims initial anonymous user implementation
                //exponent_users_login("anonymous", "anonymous");
            }

            // Handle sub themes
            $page = exponent_theme_getTheme();

            // If we are in a printer friendly request then we need to change to our printer friendly subtheme
            if (PRINTER_FRIENDLY == 1) {
                exponent_sessions_set("uilevel",0);
                $pftheme = exponent_theme_getPrinterFriendlyTheme();  	// get the printer friendly theme 
                $page = $pftheme == null ? $page : $pftheme;		// if there was no theme found then just use the current subtheme
            }

            $base_i18n = exponent_lang_loadFile('index.php');

            if (is_readable($page)) {
                // Feb 12, 2011 - trungdt - Change to get better SEO - begin
                // first, we must unset all action cache
                _ab_theme_action_clear_cache();
                // Feb 12, 2011 - trungdt - Change to get better SEO - end
                if (!exponent_javascript_inAjaxAction()) {
                    // Feb 12, 2011 - trungdt - Change to get better SEO - begin
                    // by this way, we can get better page title in action mode
                    if (exponent_theme_inAction()){
                        ob_start();
                        exponent_theme_runAction();
                        // Oct 7, 2011 - trungdt - Change the way we continue load after action by adding Flag Ajax Action
                        if (exponent_theme_getFlagAjaxAction())
                        {
                            $ret=ob_get_clean();
                            echo $ret;
                        }
                        else
                        {
                            // put content 
                            _ab_theme_action_push_content();
                        }
                        // END oCT 7
                    }
                    // Oct 7, 2011 - trungdt - Change the way we continue load after action by adding Flag Ajax Action
                    if (!exponent_theme_getFlagAjaxAction())
                    {
                        include_once($page);
                        // Feb 12, 2011 - trungdt - Change to get better SEO - end
                        exponent_theme_satisfyThemeRequirements();
                    }
                    // End Oct 7
                } else {
                    exponent_theme_runAction();
                }
            } else {
                echo sprintf($base_i18n['not_readable'], $page);
            }

            if (PRINTER_FRIENDLY == 1) {
                //$levels = exponent_sessions_get('uilevels');
                //if (!empty($levels)) exponent_sessions_set('uilevel',max(array_keys($levels)));
                exponent_sessions_unset('uilevel');
            }
        }

    }
    //$microtime_str = explode(' ',microtime());
    //$i_end = $microtime_str[0] + $microtime_str[1];
    //echo "\r\n<!--".sprintf($base_i18n['exec_time'],round($i_end - $i_start,4)).'-->';

    while (ob_get_level() > 0) {
        ob_end_flush();
    }

?>
